package cn.iocoder.yudao.module.reading.service.profile;

import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.module.reading.controller.app.profile.vo.*;
import cn.iocoder.yudao.module.reading.convert.profile.ProfileConvert;
import cn.iocoder.yudao.module.reading.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.reading.dal.mysql.user.UserMapper;
import cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.reading.service.file.ReadingFileService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

/**
 * 个人资料 Service 实现类
 *
 * @author 李晨
 */
@Service
@Slf4j
public class ProfileServiceImpl implements ProfileService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ReadingFileService readingFileService;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif");
    private static final long MAX_AVATAR_SIZE = 2 * 1024 * 1024; // 2MB

    @Override
    public ProfileInfoRespVO getUserProfile(Long userId) {
        UserDO user = validateUserExists(userId);
        return ProfileConvert.INSTANCE.convertToProfileInfo(user, staticResourceUrlUtils);
    }

    @Override
    public ProfileDetailRespVO getUserDetail(Long userId) {
        UserDO user = validateUserExists(userId);
        return ProfileConvert.INSTANCE.convertToProfileDetail(user, staticResourceUrlUtils);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(Long userId, ProfileUpdateReqVO reqVO) {
        // 校验用户存在
        validateUserExists(userId);
        
        // 注释掉手机号校验
        // if (reqVO.getPhone() != null) {
        //     validatePhoneUnique(userId, reqVO.getPhone());
        // }
        
        // 校验邮箱唯一性（如果修改了邮箱）
        if (reqVO.getEmail() != null) {
            validateEmailUnique(userId, reqVO.getEmail());
        }

        // 更新用户信息
        UserDO updateObj = ProfileConvert.INSTANCE.convertToUserDO(reqVO);
        updateObj.setId(userId);

        // 如果有头像URL，转换为相对路径存储
        if (reqVO.getAvatar() != null) {
            String relativePath = staticResourceUrlUtils.toRelativePath(reqVO.getAvatar());
            updateObj.setAvatar(relativePath);
            log.info("头像URL转换：{} -> {}", reqVO.getAvatar(), relativePath);
        }

        userMapper.updateById(updateObj);

        log.info("用户信息更新成功，用户ID: {}", userId);
    }

    @Override
    public ProfileAvatarRespVO uploadAvatar(Long userId, MultipartFile avatar) {
        // 校验用户存在
        validateUserExists(userId);

        // 校验文件
        validateAvatarFile(avatar);

        try {
            // 使用ReadingFileService上传头像到MinIO，返回相对路径
            String relativePath = readingFileService.uploadUserAvatar(userId, avatar);
            // 转换为完整URL返回给前端
            String fullUrl = staticResourceUrlUtils.toFullUrl(relativePath);

            log.info("用户头像上传成功，用户ID: {}, 相对路径: {}, 完整URL: {}", userId, relativePath, fullUrl);

            ProfileAvatarRespVO result = new ProfileAvatarRespVO();
            result.setAvatarUrl(fullUrl);
            return result;

        } catch (Exception e) {
            log.error("头像上传失败，用户ID: {}", userId, e);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AVATAR_UPLOAD_FAILED);
        }
    }

    /**
     * 校验用户存在
     */
    private UserDO validateUserExists(Long userId) {
        UserDO user = userMapper.selectById(userId);
        if (user == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.USER_NOT_EXISTS);
        }
        return user;
    }

    // 注释掉手机号唯一性校验方法
    // /**
    //  * 校验手机号唯一性
    //  */
    // private void validatePhoneUnique(Long userId, String phone) {
    //     UserDO existUser = userMapper.selectOne("phone", phone);
    //     if (existUser != null && !existUser.getId().equals(userId)) {
    //         throw ServiceExceptionUtil.exception(ErrorCodeConstants.PHONE_ALREADY_EXISTS);
    //     }
    // }

    /**
     * 校验邮箱唯一性
     */
    private void validateEmailUnique(Long userId, String email) {
        UserDO existUser = userMapper.selectOne("email", email);
        if (existUser != null && !existUser.getId().equals(userId)) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.EMAIL_ALREADY_EXISTS);
        }
    }

    /**
     * 校验头像文件
     */
    private void validateAvatarFile(MultipartFile avatar) {
        if (avatar == null || avatar.isEmpty()) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AVATAR_FILE_EMPTY);
        }
        
        if (avatar.getSize() > MAX_AVATAR_SIZE) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AVATAR_FILE_TOO_LARGE);
        }
        
        String originalFilename = avatar.getOriginalFilename();
        if (originalFilename == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AVATAR_FILE_INVALID);
        }
        
        String extension = FileUtil.extName(originalFilename).toLowerCase();
        if (!ALLOWED_EXTENSIONS.contains(extension)) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.AVATAR_FILE_TYPE_INVALID);
        }
    }

}
